package com.jagochan.imchat.module.common.interceptor;

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 用于收集需要共享的上下文信息的拦截器
 */
@Component
public class ContextInfoCollectInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long uid = Optional.ofNullable(request.getAttribute(TokenInterceptor.UID_KEY)).map(v -> Long.parseLong(v.toString())).orElse(null);
        String ip = ServletUtil.getClientIP(request);
        ContextInfoHolder.set(uid, ip);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ContextInfoHolder.remove();
    }
}
